using System;
using LS.Entity;
using UnityEngine;
using Unity.VisualScripting;

namespace LS.VisualScripting
{
    public class ShowEntityWithTransform : EntityUnit
    {
        [Serialize]
        [Inspectable, UnitHeaderInspectable]
        [TypeFilter(typeof(EntityBase))]
        public System.Type EntityLogicType { get; private set; } = null;
         
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueInput EntityTypeId { get; set; }
        
        [DoNotSerialize]
        public ValueInput Position { get; set; }
        
        [DoNotSerialize]
        public ValueInput Rotation { get; set; }
        
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueInput UserData { get; set; }
        
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueOutput SerialId { get; set; }
        
        protected override void Definition()
        {
            base.Definition();
            EntityTypeId = ValueInput<int>(nameof(EntityTypeId), 0);
            UserData = ValueInput<object>(nameof(UserData), null);
            Position = ValueInput<Vector3>(nameof(UserData), Vector3.zero);
            Rotation = ValueInput<Quaternion>(nameof(UserData), Quaternion.identity);
            SerialId = ValueOutput<int>(nameof(SerialId));
            Requirement(EntityTypeId, Input);
            Requirement(Position, Input);
            Requirement(Rotation, Input);
            Requirement(UserData, Input);
        }

        protected override ControlOutput In(Flow flow)
        {
            int entityId = flow.GetValue<int>(EntityTypeId);
            object userData = flow.GetValue<object>(UserData);
            Vector3 pos = flow.GetValue<Vector3>(Position);
            Quaternion ro = flow.GetValue<Quaternion>(Rotation);
            EntityParams parm = null;
            if (userData is not null && userData is EntityParams)
            {
                parm = (EntityParams)userData;
            }
            else
            {
                parm = EntityParams.Create<EntityParams>(userData);
            }
            parm.Position = pos;
            parm.Rotation = ro;
            
            int serialId = Target?.ShowEntity(entityId, EntityLogicType, parm) ?? 0;
            flow.SetValue(SerialId, serialId);
            return base.In(flow);
        }
    }
}